package com.huterox.todoscheduler.common;

import java.io.File;

import java.io.*;

public class SerializationUtils implements Serializable {

    private static final String DEFAULT_DIRECTORY = "src/main/resources";

    public static void serializeObject(Object object, String fileName) {
        serializeObject(object, DEFAULT_DIRECTORY, fileName);
    }

    public static Object deserializeObject(String fileName) {
        return deserializeObject(DEFAULT_DIRECTORY, fileName);
    }

    public static void serializeObject(Object object, String directory, String fileName) {
        try {
            // 创建目录
            File dir = new File(directory);
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    System.out.println("目录已创建: " + directory);
                } else {
                    System.out.println("无法创建目录: " + directory);
                    return;
                }
            }

            // 序列化对象
            FileOutputStream fileOut = new FileOutputStream(directory + "/" + fileName);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(object);
            out.close();
            fileOut.close();
            System.out.println("对象已序列化并保存到文件: " + directory + "/" + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object deserializeObject(String directory, String fileName) {
        Object object = null;
        try {
            // 反序列化对象
            FileInputStream fileIn = new FileInputStream(directory + "/" + fileName);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            object = in.readObject();
            in.close();
            fileIn.close();
            System.out.println("从文件中反序列化出对象: " + directory + "/" + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    public static void deleteSerializedObject(String directory, String fileName) {
        try {
            File file = new File(directory + "/" + fileName);
            if (file.exists()) {
                if (file.delete()) {
                    System.out.println("文件删除成功: " + directory + "/" + fileName);
                } else {
                    System.out.println("无法删除文件: " + directory + "/" + fileName);
                }
            } else {
                System.out.println("文件不存在: " + directory + "/" + fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
